package com.xy.view.test;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

import com.a520it.generalutils.R;
import com.nineoldandroids.animation.ArgbEvaluator;
import com.xy.debug.SystemConfig;

/**
 * Created by John on 2016/11/30.
 */

public class ZimaView extends View {

    private int maxNum;
    private int startAngle;
    private int sweepAngle;
    private Paint paint;
    private int sweepInWidth;
    private int sweepOutWidth;
    private int radius;
    private int currentNum;
    private int mW;

    public ZimaView(Context context) {
        this(context, null);
    }

    public ZimaView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZimaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ZimaView);
        maxNum = array.getInt(R.styleable.ZimaView_maxNum, 1000);
        startAngle = array.getInt(R.styleable.ZimaView_startAngle, 160);
        sweepAngle = array.getInt(R.styleable.ZimaView_sweepAngle, 220);
        sweepInWidth = SystemConfig.dp2px(getContext(), 8);
        sweepOutWidth = SystemConfig.dp2px(getContext(), 3);
        currentNum = 0;
        mW = SystemConfig.dp2px(getContext(), 10);  //内外圆间距
        array.recycle();
        init(context);
    }

    private void init(Context context) {
        initPaint();
    }

    private void initPaint() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setDither(true);  //防抖动
        paint.setStyle(Paint.Style.STROKE);
    }

    public void setCurrentNum(int currentNum) {
        this.currentNum = currentNum;
        invalidate();
    }

    public int getCurrentNum() {
        return currentNum;
    }

    public void setCurrentNumAnim(int num) {
        long duraction = (long) Math.abs(num - currentNum) / 1500 + 500;
        duraction = Math.min(duraction, 2000);
        ObjectAnimator anInt = ObjectAnimator.ofInt(this, "currentNum", num);
        anInt.setDuration(duraction);
        anInt.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                int color = caclulateColor(value);
                setBackgroundColor(color);
            }
        });
        anInt.start();
    }

    private int caclulateColor(int value) {
        ArgbEvaluator evaluator = new ArgbEvaluator();
        float fraction = 0;
        int color = 0;
        if (value <= maxNum / 2) {
            fraction = (float) value / (maxNum / 2);
            color = (int) evaluator.evaluate(fraction, 0xffff6347, 0xffff8c00);
        } else {
            fraction = (float) (value - maxNum / 2) / (maxNum / 2);
            color = (int) evaluator.evaluate(fraction, 0xffff8c00, 0xff00ced1);
        }
        return color;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureWidth(widthMeasureSpec);
        int height = MeasureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int MeasureWidth(int widthMeasureSpec) {
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        int width = 0;
        if (mode == MeasureSpec.EXACTLY) {
            width = size;
        } else {
            width = SystemConfig.dp2px(getContext(), 300);
        }
        return width;
    }

    private int MeasureHeight(int heightMeasureSpec) {
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);
        int height = 0;
        if (mode == MeasureSpec.EXACTLY) {
            height = size;
        } else {
            height = SystemConfig.dp2px(getContext(), 400);
        }
        return height;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        radius = Math.min(getMeasuredHeight(), getMeasuredWidth()) / 4;
        canvas.save();
        canvas.translate(getMeasuredWidth() / 2, getMeasuredHeight() / 2);  //将画布移到view中心
        drawArc(canvas);  //画弧
        drawLine(canvas); //画刻度线
        drawPoint(canvas);//画点
        drawCenterText(canvas);
        canvas.restore();
    }

    private void drawCenterText(Canvas canvas) {
        canvas.save();
        String s = "信用";
        Paint cen = new Paint();
        cen.setFlags(Paint.ANTI_ALIAS_FLAG);
        cen.setStyle(Paint.Style.FILL);
        cen.setColor(0xffffffff);
        cen.setTextSize(radius / 2);
        canvas.drawText(currentNum + "", -cen.measureText(currentNum + "") / 2, 0, cen);
        int rate = maxNum / 5;
        if (currentNum >= 0 && currentNum < rate) {
            s += str[0];
        } else if (currentNum >= rate && currentNum < 2 * rate) {
            s += str[1];
        } else if (currentNum >= 2 * rate && currentNum < 3 * rate) {
            s += str[2];
        } else if (currentNum >= 3 * rate && currentNum < 4 * rate) {
            s += str[3];
        } else if (currentNum >= 4 * rate) {
            s += str[4];
        }
        cen.setTextSize(radius / 4);
        Rect r = new Rect();
        cen.getTextBounds(s, 0, s.length(), r);
        canvas.drawText(s, -r.width() / 2, r.height() + 20, cen);
        canvas.restore();
    }

    private void drawPoint(Canvas canvas) {
        canvas.save();
        Paint indic = new Paint();
        indic.setStyle(Paint.Style.STROKE);
        indic.setColor(0xffffffff);
        indic.setStrokeWidth(sweepOutWidth);
        SweepGradient gradient = new SweepGradient(0, 0, new int[]{0xffffffff, 0x00ffffff, 0x99ffffff, 0xffffffff}, null);//	渲染中心点x 坐标，y坐标,颜色变化数组，相对位置的颜色数组,可为null, 若为null,可为null,颜色沿渐变线均匀分布
        indic.setShader(gradient);
        float sweep;
        if (currentNum <= maxNum) {
            sweep = currentNum * 1.0f / maxNum * sweepAngle;
        } else {
            sweep = sweepAngle;
        }
        RectF rectF = new RectF(-radius - mW, -radius - mW, radius + mW, radius + mW);
        canvas.drawArc(rectF, (float) startAngle, sweep, false, indic);
        Paint pointP = new Paint();
        pointP.setStyle(Paint.Style.FILL);
        pointP.setColor(0xffffffff);
        //点的xy坐标
        double x = (radius + mW) * Math.cos(Math.toRadians(startAngle + sweep));//转化为弧度为单位的角度
        double y = (radius + mW) * Math.sin(Math.toRadians(startAngle + sweep));//转化为弧度为单位的角度
        canvas.drawCircle((float) x, (float) y, sweepOutWidth, pointP);
        canvas.restore();
    }

    private String[] str = new String[]{"恶劣", "差", "良", "好", "非常好"};

    private void drawLine(Canvas canvas) {
        canvas.save();
        canvas.rotate(-270 + startAngle);  //顺时针为负  将刻度起始点定在y轴上半轴  刻度起始点旋转 -270+startAngle。
        float angle = (float) sweepAngle / 30;//分成30个刻度间隔
        for (int i = 0; i <= 30; i++) {
            if (i % 6 == 0) {  //画大刻度
                paint.setStrokeWidth(SystemConfig.dp2px(getContext(), 2));
                paint.setAlpha(0x70);
                canvas.drawLine(0, -radius - sweepInWidth / 2, 0, -radius + sweepInWidth / 2 + SystemConfig.dp2px(getContext(), 2), paint);   //view的原点已经移到中心
                drawText(canvas, i * maxNum / 30 + "", paint);
            } else {  //画小刻度
                //设置线宽 就是在原来的宽度上向两边各延伸一般的宽度。
                paint.setStrokeWidth(SystemConfig.dp2px(getContext(), 1));
                paint.setAlpha(0x50);
                canvas.drawLine(0, -radius - sweepInWidth / 2, 0, -radius + sweepInWidth / 2, paint);   //view的原点已经移到中心
            }
            if (i == 3 || i == 9 || i == 15 || i == 21 || i == 27) {
                drawText(canvas, str[(i + 3) / 6 - 1], paint);
            }
            canvas.rotate(angle);
        }
        canvas.restore();
    }

    private void drawText(Canvas canvas, String i, Paint paint) {
        paint.setTextSize(SystemConfig.sp2px(getContext(), 14));
        paint.setStyle(Paint.Style.FILL);
        float textWidth = paint.measureText(i);
        canvas.drawText(i, -(textWidth / 2), -radius + sweepInWidth / 2 + SystemConfig.dp2px(getContext(), 16), paint);
        paint.setStyle(Paint.Style.STROKE);
    }

    private void drawArc(Canvas canvas) {
        canvas.save();
        paint.setColor(0xffffffff);
        paint.setAlpha(0x40);
        paint.setStrokeWidth(sweepInWidth);  //画内圆
        RectF Inrectf = new RectF(-radius, -radius, radius, radius);
        //开始角度从x轴正方向为顺时针为正，sweepAngle为扫过的角度
        canvas.drawArc(Inrectf, startAngle, sweepAngle, false, paint);

        paint.setStrokeWidth(sweepOutWidth);
        RectF OutRecf = new RectF(-radius - mW, -radius - mW, radius + mW, radius + mW);
        canvas.drawArc(OutRecf, startAngle, sweepAngle, false, paint);
        canvas.restore();
    }
}
